package com.gf.message.controller;

import java.util.Arrays;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.gf.base.controller.BasicController;
import com.gf.base.type.MessageType;
import com.gf.common.bean.DataRequest;
import com.gf.common.bean.DataResponse;
import com.gf.common.bean.Page;
import com.gf.common.constant.Constants;
import com.gf.common.constant.ViewPaths;
import com.gf.common.staticer.MessageRemainsHelper;
import com.gf.common.util.StrArrayHelper;
import com.gf.common.util.WebHelper;
import com.gf.message.service.MessageService;
import com.gf.user.model.User;

/**
 * 站内消息<br>
 * 给管理员发送消息是免费的
 * 
 * @author zhuguifeng
 * 
 */
@Controller
@RequestMapping("message")
public class MessageController extends BasicController {
	@Autowired
	private MessageService messageService;

	private static Log log = LogFactory.getLog(MessageController.class);

	/**
	 * 消息主页
	 * 
	 * @return
	 */
	@RequestMapping(value = "/index", method = RequestMethod.GET)
	public ModelAndView messageIndex() {
		log.info("信息:主页");

		User user = WebHelper.getSessionUser();
		long userId = user.getId();
		int unReadMsgCount = MessageRemainsHelper.getRemains(userId);

		ModelAndView mvc = new ModelAndView();
		mvc.setViewName(ViewPaths.MESSAGE_INDEX_VIEW);
		mvc.addObject("user", user);
		mvc.addObject("messageCount", unReadMsgCount);

		return mvc;
	}

	/**
	 * 写消息
	 * 
	 * @return
	 */
	@RequestMapping(value = "/write", method = RequestMethod.GET)
	public ModelAndView write() {
		log.info("写信息");

		User user = WebHelper.getSessionUser();
		long userId = user.getId();
		int unReadMsgCount = MessageRemainsHelper.getRemains(userId);

		ModelAndView mvc = new ModelAndView();
		mvc.addObject("user", user);
		mvc.addObject("messageCount", unReadMsgCount);
		mvc.setViewName(ViewPaths.MESSAGE_WRITE);

		return mvc;
	}

	/**
	 * 发件箱
	 * 
	 * @return
	 */
	@RequestMapping(value = "/outbox", method = RequestMethod.GET)
	public ModelAndView messageInbox() {
		log.info("信息:发件箱");

		User user = WebHelper.getSessionUser();
		long userId = user.getId();
		int total = messageService.getNumberByMessageType(userId,
				MessageType.OUTBOX);

		ModelAndView mvc = new ModelAndView();
		mvc.setViewName(ViewPaths.MESSAGE_OUTBOX);
		mvc.addObject("total", total);
		return mvc;
	}

	/**
	 * 收件箱
	 * 
	 * @return
	 */
	@RequestMapping(value = "/inbox", method = RequestMethod.GET)
	public ModelAndView messageOutbox() {
		log.info("信息:收件箱");

		User user = WebHelper.getSessionUser();
		long userId = user.getId();
		int unReadMsgCount = MessageRemainsHelper.getRemains(userId);

		ModelAndView mvc = new ModelAndView();
		mvc.setViewName(ViewPaths.MESSAGE_INBOX);
		mvc.addObject("unReadMsgCount", unReadMsgCount);

		return mvc;
	}

	/**
	 * 草稿箱
	 * 
	 * @return
	 */
	@RequestMapping(value = "/draft", method = RequestMethod.GET)
	public ModelAndView messageDraft() {
		log.info("信息:草稿箱");

		User user = WebHelper.getSessionUser();
		long userId = user.getId();
		int draft = messageService.getNumberByMessageType(userId,
				MessageType.DRAFT);

		ModelAndView mvc = new ModelAndView();
		mvc.setViewName(ViewPaths.MESSAGE_DRAFT);
		mvc.addObject("draft", draft);

		return mvc;
	}

	@RequestMapping(value = "/loadInboxData", method = RequestMethod.POST)
	public @ResponseBody
	DataResponse getInBoxMessage(DataRequest dataRequest) {

		User user = WebHelper.getSessionAttribute(Constants.SESSION_USER);
		if (user == null) {
			return new DataResponse();
		}

		int curpage = dataRequest.getPage();
		int pageSize = dataRequest.getRows();
		long userId = user.getId();
		Page page = messageService.getAllReceiveMessages(userId, curpage,
				pageSize);

		DataResponse dataResponse = new DataResponse();
		dataResponse.setResult(page.getResults());
		dataResponse.setPage(page.getCurpage());
		dataResponse.setRecords(page.getTotal());
		dataResponse.setTotal(page.getTotalPage());

		return dataResponse;
	}

	@RequestMapping(value = "/loadOutboxData", method = RequestMethod.POST)
	public @ResponseBody
	DataResponse getOutBoxMessage(DataRequest dataRequest) {
		log.info("信息:发件箱");

		User user = WebHelper.getSessionAttribute(Constants.SESSION_USER);
		if (user == null) {
			return new DataResponse();
		}

		int curpage = dataRequest.getPage();
		int pageSize = dataRequest.getRows();
		long userId = user.getId();
		Page page = messageService
				.getAllSendMessages(userId, curpage, pageSize);

		DataResponse dataResponse = new DataResponse();
		dataResponse.setResult(page.getResults());
		dataResponse.setPage(page.getCurpage());
		dataResponse.setRecords(page.getTotal());
		dataResponse.setTotal(page.getTotalPage());

		return dataResponse;
	}

	@RequestMapping(value = "/loaddraftData", method = RequestMethod.POST)
	public @ResponseBody
	DataResponse getDraftMessage(DataRequest dataRequest) {
		log.info("信息: 草稿");
		User user = WebHelper.getSessionAttribute(Constants.SESSION_USER);
		if (user == null) {
			return new DataResponse();
		}

		int curpage = dataRequest.getPage();
		int pageSize = dataRequest.getRows();
		long userId = user.getId();
		Page page = messageService.getAllDraftMessages(userId, curpage,
				pageSize);

		DataResponse dataResponse = new DataResponse();
		dataResponse.setResult(page.getResults());
		dataResponse.setPage(page.getCurpage());
		dataResponse.setRecords(page.getTotal());
		dataResponse.setTotal(page.getTotalPage());

		return dataResponse;
	}

	/**
	 * 单发
	 */
	@RequestMapping(value = "/sendByOne", method = RequestMethod.POST)
	public @ResponseBody
	boolean sendMessageByOne(long receiveId, String title, String content) {
		User sender = WebHelper.getSessionAttribute(Constants.SESSION_USER);
		if (sender == null) {
			return false;
		}

		log.info("发送信息：" + sender.getId() + "--->" + receiveId);

		long result = messageService.sendMessageByOne(sender.getId(),
				sender.getNickname(), receiveId, title, content);

		return result > 0 ? true : false;
	}

	/**
	 * 群发
	 * 
	 * @param receiveIds
	 * @param title
	 * @param content
	 * @return
	 */
	@RequestMapping(value = "/sendByGroup", method = RequestMethod.POST)
	public @ResponseBody
	boolean sendMessageByGroup(Long[] receiveIds, String title, String content) {
		User sender = WebHelper.getSessionAttribute(Constants.SESSION_USER);
		if (sender == null) {
			return false;
		}

		log.info("群发信息：" + sender.getId());

		if (receiveIds.length == 0) {
			return false;
		} else if (receiveIds.length == 1) {
			long result = messageService.sendMessageByOne(sender.getId(),
					sender.getNickname(), receiveIds[0], title, content);

			return result > 0 ? true : false;
		} else {
			int n = messageService.sendMessageByGroup(sender.getId(),
					sender.getNickname(), receiveIds, title, content);

			return n == receiveIds.length ? true : false;
		}

	}

	/**
	 * 保存为草稿<br>
	 * 由于 数据库Message设计的局限性<br>
	 * 当保存为草稿时 receiveId = senderId, senderName=receiveName<br>
	 * draftReceiveIds 保存着要接收的联系人ID： 3-4-12
	 * 
	 * @return
	 */
	@RequestMapping(value = "/saveAsDraft", method = RequestMethod.POST)
	public @ResponseBody
	boolean saveAsDraft(String title, String content, Long[] receiveIds,
			String[] draftReceiveNames) {
		User sender = WebHelper.getSessionAttribute(Constants.SESSION_USER);
		if (sender == null) {
			return false;
		}

		long result = messageService
				.saveAsDraft(
						sender.getId(),
						sender.getNickname(),
						StrArrayHelper.listToStr(Arrays.asList(receiveIds), "-"),
						StrArrayHelper.listToStr(
								Arrays.asList(draftReceiveNames), "-"), title,
						content);

		return result > 0 ? true : false;
	}

	/**
	 * 
	 * @param id
	 */
	@RequestMapping(value = "/changeState", method = RequestMethod.POST)
	public @ResponseBody
	void changeState(int id) {
		User user = WebHelper.getSessionAttribute(Constants.SESSION_USER);
		if (user == null) {
			return;
		}
		messageService.messageReaded(id);
		MessageRemainsHelper.readMessageByOne(user.getId());
	}

	/**
	 * 
	 * @param id
	 */
	@RequestMapping(value = "/deleteMessageBySender", method = RequestMethod.POST)
	public @ResponseBody
	void deleteMessageBySender(int id) {
		User user = WebHelper.getSessionAttribute(Constants.SESSION_USER);
		if (user == null) {
			return;
		}
		messageService.deleteMessageBySender(id);
	}

	/**
	 * 
	 * @param id
	 */
	@RequestMapping(value = "/deleteDraft", method = RequestMethod.POST)
	public @ResponseBody
	void deleteDraft(int id) {
		User user = WebHelper.getSessionAttribute(Constants.SESSION_USER);
		if (user == null) {
			return;
		}
		messageService.deleteDraft(id);
	}

	/**
	 * 
	 * @param id
	 */
	@RequestMapping(value = "/deleteMessageByReceiver", method = RequestMethod.POST)
	public @ResponseBody
	void deleteMessageByReceiver(int id) {
		User user = WebHelper.getSessionAttribute(Constants.SESSION_USER);
		if (user == null) {
			return;
		}
		messageService.deleteMessageByReceiver(id);
	}
}
